<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { School } from '@/api/modules/schools'
import type { FormInstance, FormRules } from 'element-plus'
import apiSchool from '@/api/modules/schools'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'

const updateImg = ref(false)
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  schoolId: route.params.id as string | number ?? '',
  schoolName: '',
  province: '',
  city: '',
  schoolLogo: '',
  schoolNameEn: '',
})

const formRules = ref<FormRules>({
  schoolName: [
    { required: true, message: '请输入学校名称', trigger: 'blur' },
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' },
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' },
  ],
})

onMounted(() => {
  if (form.value.schoolId !== '') {
    getInfo()
  }
})

function getInfo() {
  loading.value = true
  apiSchool.detail(form.value.schoolId).then((res: any) => {
    loading.value = false
    const data = res.data.data // 提取数据
    // 完整映射所有字段
    form.value.schoolId = data.schoolId
    form.value.schoolName = data.schoolName
    form.value.province = data.province
    form.value.city = data.city
    form.value.schoolNameEn = data.schoolNameEn
    if (form.value.schoolLogo === '') {
      form.value.schoolLogo = data.schoolLogo
    }
  })
}

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        // 构造符合 School 接口的对象
        const schoolData = {
          schoolId: Number(form.value.schoolId),
          schoolName: form.value.schoolName,
          province: form.value.province,
          schoolLogo: form.value.schoolLogo,
          schoolNameEn: form.value.schoolNameEn,
        } as School
        if (form.value.schoolId === '') {
          apiSchool.create(schoolData).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
        else {
          form.value.schoolId = Number(form.value.schoolId)
          apiSchool.edit(schoolData).then(() => {
            ElMessage.success({
              message: '编辑成功',
            })
            goBack()
          })
        }
      }
    })
  })
}
function onCancel() {
  goBack()
}
// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'logoList' })
  }
  else {
    router.push({ name: 'logoList' })
  }
}
async function handleLogoSuccess(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiSchool.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.schoolLogo = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'schoolManagementCreate' ? '新增学校' : '编辑学校logo'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="130px" label-suffix="：" class="custom-form">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <ElFormItem label="学校名称" prop="schoolName">
          <ElInput v-model="form.schoolName" placeholder="请输入学校名称" disabled />
        </ElFormItem>

        <ElFormItem label="学校英文名称" prop="schoolNameEn">
          <ElInput v-model="form.schoolNameEn" placeholder="请输入学校英文名称" disabled />
        </ElFormItem>

        <ElFormItem label="省份" prop="province">
          <ElInput v-model="form.province" placeholder="请输入省份" disabled />
        </ElFormItem>

        <ElFormItem label="城市" prop="city">
          <ElInput v-model="form.city" placeholder="请输入城市" disabled />
        </ElFormItem>

        <ElFormItem label="上传logo" prop="schoolLogo">
          <ImageUpload
            v-model="form.schoolLogo"
            :loading="updateImg"
            action="" name="schoolLogo"
            :width="150"
            :height="150"
            :http-request="handleLogoSuccess"
          />
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
</style>
